package cn.go.buster.launcher.api;

import android.os.Looper;

/**
 * @author logcat
 * @date 2020/07/17
 */
public class GoBuster extends Poster {


    private Object[] defaultParams;

    private GoBuster() {
        super();
        defaultParams = new Object[]{};
    }


    public static IPoster getInstance() {
        if (instance == null) {
            synchronized (GoBuster.class) {
                if (instance == null) {
                    instance = new GoBuster();
                }
            }
        }
        return instance;
    }


    /**
     * Post an event without parameters.
     *
     * @param tag A mark for event.
     */
    @Override
    public void post(String tag) {
        post(tag, defaultParams);
    }


    /**
     * Post an event with some parameters。
     *
     * @param tag    A mark for event.
     * @param params Some parameters you want to send.
     */

    @Override
    public void post(String tag, Object... params) {
        runOnMainThread(new Runnable() {
            @Override
            public void run() {
                try {
                    EventCenter.getInstance().post(tag, params);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * Register GoBuster
     *
     * @param objectNode
     */
    @Override
    public void register(Object objectNode) {

        runOnChildThread(new Runnable() {
            @Override
            public void run() {
                EventCenter.getInstance().register(objectNode);
            }
        });
    }


    /**
     * Unregister GoBuster
     *
     * @param objectNode
     */
    @Override
    public void unRegister(Object objectNode) {
        runOnChildThread(new Runnable() {
            @Override
            public void run() {
                EventCenter.getInstance().unRegister(objectNode);
            }
        });


        if (currentRunnable != null) {
            getHandler().removeCallbacks(currentRunnable);
            getMainThreadHandler().removeCallbacks(currentRunnable);

            currentRunnable = null;
        }
    }


    /**
     * Run something on child thread.
     *
     * @param runnable
     */
    private static void runOnChildThread(Runnable runnable) {
        Poster.get().setCurrentRunnable(runnable);
        Poster.get().getHandler().post(runnable);
    }


    /**
     * Run something on UI thread.
     *
     * @param runnable
     */
    private static void runOnMainThread(Runnable runnable) {
        Poster.get().setCurrentRunnable(runnable);
        //If not on main thread.
        if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
            Poster.get().getMainThreadHandler().post(runnable);
        } else {
            //If is on main thread.
            Poster.get().getHandler().post(runnable);
        }
    }
}
